package net.hn.hnms.biz.equipment.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.hn.hnms.biz.equipment.domain.CoalMineSysPointPo;
import net.hn.hnms.biz.equipment.domain.KsjjHisPo;
import net.hn.hnms.biz.equipment.domain.dto.*;
import net.hn.hnms.biz.equipment.domain.vo.*;
import net.hn.hnms.biz.equipment.mapper.CoalMineSysPointMapper;
import net.hn.hnms.biz.equipment.mapper.KsjjHisMapper;
import net.hn.hnms.biz.equipment.service.CoalMineSysPointService;
import net.hn.hnms.biz.equipment.service.DrivageService;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 快速掘进实现类
 */
@Service
public class DrivageServiceImpl implements DrivageService {

    @Resource
    private CoalMineSysPointMapper coalMineSysPointMapper;

    @Resource
    private CoalMineSysPointService coalMineSysPointService;

    /**
     * 快速掘进历史数据Mapper
     */
    @Resource
    private KsjjHisMapper ksjjHisMapper;

    /**
     * 获取所属设备下拉列表
     * @return
     */
    @Override
    public List<String> categoryList(String mineCode) {
        LambdaQueryWrapper<CoalMineSysPointPo> coalMineSysPointPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询所有快速掘进的设备
        coalMineSysPointPoLambdaQueryWrapper.like(CoalMineSysPointPo::getApiCategory, "drivage");
        coalMineSysPointPoLambdaQueryWrapper.eq(StringUtils.isNotEmpty(mineCode),CoalMineSysPointPo::getMineCode, mineCode);
        List<CoalMineSysPointPo> coalMineSysPointPoList = coalMineSysPointMapper.selectList(coalMineSysPointPoLambdaQueryWrapper);
        List<String> collect = coalMineSysPointPoList.stream().map(t -> {
            String s = new String();
            s = t.getDeviceName();
            return s;
        }).distinct().collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取设备位置下拉列表
     * @return
     */
    @Override
    public List<String> deviceLocaltionList(String mineCode) {
        LambdaQueryWrapper<CoalMineSysPointPo> coalMineSysPointPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询所有快速掘进的设备
        coalMineSysPointPoLambdaQueryWrapper.like(CoalMineSysPointPo::getApiCategory, "drivage");
        coalMineSysPointPoLambdaQueryWrapper.eq(StringUtils.isNotEmpty(mineCode),CoalMineSysPointPo::getMineCode, mineCode);
        List<CoalMineSysPointPo> coalMineSysPointPoList = coalMineSysPointMapper.selectList(coalMineSysPointPoLambdaQueryWrapper);
        List<String> collect = coalMineSysPointPoList.stream().map(t -> {
            String s = new String();
            s = t.getApiPage() + "工作面";
            return s;
        }).distinct().collect(Collectors.toList());
        return collect;
    }
    /**
     * 分页条件查询快速掘进实时数据
     *
     * @param pageQuery
     * @param nowDTO
     * @return
     */
    @Override
    public ResponsePage<NowVo> pageNowList(PageQuery pageQuery, NowDto nowDTO) {
        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize():0);

        // 所属设备
        // 设备位置 去掉“工作面”三个字
        String deviceLocation = nowDTO.getDeviceLocation();
        nowDTO.setDeviceLocation(StringUtils.isNotEmpty(deviceLocation)?deviceLocation.replace("工作面", ""):null);

        List<SynergiaSysPointDto> list=coalMineSysPointMapper.selectDrivagePageList(pageQuery.getPageSize(), pageQuery.getPageNum(), nowDTO);
        if (list.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        List<NowVo> collect = list.stream().map(t -> {
            NowVo nowVo = new NowVo();
            //测点编码
            nowVo.setPointCode(t.getPointCode());
            //所属设备
            nowVo.setCategory(t.getDeviceName());
            //设备位置
            nowVo.setDeviceLocation(t.getApiPage() + "工作面");
            //测点名称
            nowVo.setPonitName(t.getApiNameCn());
            //数值类型
            nowVo.setValueType(coalMineSysPointService.valueTypeTransitionString(t.getValueType()));
            //检测值
            nowVo.setValue(t.getPointValue());
            //数值单位
            nowVo.setValueUnit(StringUtils.isNotEmpty(t.getSensorUnit())?t.getSensorUnit():"-");
            //检测说明
            nowVo.setValueContent(t.getRemark());
            //数据质量
            nowVo.setDataUality(coalMineSysPointService.dataUalityTransitionString(t.getPointStatus()));
            //数据时间
            nowVo.setDateTime(t.getDataTime());
            return nowVo;
        }).collect(Collectors.toList());
//        collect.stream().sorted(Comparator.comparing(NowVo::getDateTime).reversed()).collect(Collectors.toList());
        return new ResponsePage<>(collect, list.get(0).getTotal());

    }
    /**
     * 分页条件查询历史数据
     *
     * @param pageQuery
     * @param hisDTO
     * @return
     */
    @Override
    public ResponsePage<HisVo> pageHistoryInfo(PageQuery pageQuery, HisDto hisDTO) {
        pageQuery.setPageNum(pageQuery.getPageNum() >= 1 ? pageQuery.getPageNum() * pageQuery.getPageSize():0);

        // 所属设备
        // 设备位置 去掉“工作面”三个字
        String deviceLocation = hisDTO.getDeviceLocation();
        hisDTO.setDeviceLocation(StringUtils.isNotEmpty(deviceLocation)?deviceLocation.replace("工作面", ""):null);

        List<SynergiaSysPointDto> list=coalMineSysPointMapper.selectDrivageHisPageList(pageQuery.getPageSize(), pageQuery.getPageNum(), hisDTO);
        if (list.isEmpty()) {
            return new ResponsePage<>(new ArrayList(), 0);
        }
        List<HisVo> collect = list.stream().map(t -> {
            HisVo hisVo = new HisVo();
            //测点编码
            hisVo.setPointCode(t.getPointCode());
            //所属设备
            hisVo.setCategory(t.getDeviceName());
            //设备位置
            hisVo.setDeviceLocation(t.getApiPage() + "工作面");
            //测点名称
            hisVo.setPonitName(t.getApiNameCn());
            //数值类型
            hisVo.setValueType(coalMineSysPointService.valueTypeTransitionString(t.getValueType()));
            //检测值
            hisVo.setValue(t.getPointValue());
            //数值单位
            hisVo.setValueUnit(StringUtils.isNotEmpty(t.getSensorUnit())?t.getSensorUnit():"-");
            //检测说明
            hisVo.setValueContent(t.getRemark());
            //数据质量
            hisVo.setDataUality(coalMineSysPointService.dataUalityTransitionString(t.getPointStatus()));
            //数据时间
            hisVo.setDateTime(t.getDataTime());
            return hisVo;
        }).collect(Collectors.toList());
        List<HisVo> collectVo = collect.stream().sorted(Comparator.comparing(HisVo::getDateTime).reversed()).collect(Collectors.toList());
        return new ResponsePage<>(collectVo,list.get(0).getTotal());

    }

    /**
     * 报警动态
     * @return
     */
    @Override
    public List<DrivageNowAlarmVo> alarmNowInfo(String valueType, Integer value, String mineCode) {
        if (StringUtils.isEmpty(valueType)) {
            //如果数值类型为空，则默认为Bj
         valueType = "BJ";

        }
        if (value == null) {
         value = 1;
        }

        List<SynergiaSysPointDto> list=coalMineSysPointMapper.selectDrivageNowInfo(valueType,value,mineCode);
        List<DrivageNowAlarmVo> drivageNowAlarmVoList = list.stream().map(t -> {
            //报警动态返回Vo
            DrivageNowAlarmVo drivageNowAlarmVo = new DrivageNowAlarmVo();
            //报警设备
            drivageNowAlarmVo.setDevice(t.getDeviceName());
            //报警描述
            drivageNowAlarmVo.setDescribe(t.getApiNameCn());
            //数据时间
            drivageNowAlarmVo.setDataTime(t.getDataTime());
            return drivageNowAlarmVo;
        }).collect(Collectors.toList());
        return drivageNowAlarmVoList;
    }
    /**
     * 条件查询历史数据测点曲线
     * @param pointDto
     * @return
     */
    @Override
    public ChartDateVo pointHistoryCurve(PointDto pointDto) {
        //1天内 日期间隔不做处理
        //1~3天 日期间隔5分钟 取最大值
        //3天~1月  日期间隔1小时 取最大值
        //超过1月  返回前端消息，查询时间范围为一个月

        //查询得数据集合
        List<KsjjHisPo> coalflowHisPos = null;
        //返回得数据集合Vo
        ChartDateVo chartDateVo = new ChartDateVo();
        List<Date> dateList = new ArrayList<>();
        List<BigDecimal> bigDecimalList = new ArrayList<>();


        if (pointDto.getEndTime().getTime() - pointDto.getStartTime().getTime() <= 3600 * 24 * 1 * 1000L) {
            LambdaQueryWrapper<KsjjHisPo> queryWrapper = new LambdaQueryWrapper<>();
            //一天内得数据
            queryWrapper.ge(KsjjHisPo::getDataTime,pointDto.getStartTime());
            //结束时间
            queryWrapper.le(pointDto.getEndTime() != null, KsjjHisPo::getDataTime, pointDto.getEndTime());
            queryWrapper.eq(KsjjHisPo::getPointCode, pointDto.getPointCode());

            //煤矿编码
            queryWrapper.eq(StringUtils.isNotEmpty(pointDto.getMineCode()),KsjjHisPo::getMineCode,pointDto.getMineCode());
            coalflowHisPos = ksjjHisMapper.selectList(queryWrapper);
        } else if (pointDto.getEndTime().getTime() - pointDto.getStartTime().getTime() <= 3600 * 24 * 3 * 1000L) {
            //三天内得数据
            List<ChartDto> chartDtoList= ksjjHisMapper.selectOneDayList(pointDto);
            for (ChartDto chartDto : chartDtoList) {
                dateList.add(chartDto.getTime());
                bigDecimalList.add(chartDto.getValue());
            }
            chartDateVo.setDate(dateList);
            chartDateVo.setValue(bigDecimalList);
            return chartDateVo;
        } else if (pointDto.getEndTime().getTime() - pointDto.getStartTime().getTime() <= 3600 * 24 * 31 * 1000L) {
            //1月内得数据
            List<ChartDto> chartDtoList= ksjjHisMapper.selectOneMonthList(pointDto);
            for (ChartDto chartDto : chartDtoList) {
                dateList.add(chartDto.getTime());
                bigDecimalList.add(chartDto.getValue());
            }
            chartDateVo.setDate(dateList);
            chartDateVo.setValue(bigDecimalList);
            return chartDateVo;
        }

        if (coalflowHisPos.isEmpty()) {

            chartDateVo.setDate(dateList);
            chartDateVo.setValue(bigDecimalList);
            return chartDateVo;
        }
        //list 降序排列
        List<KsjjHisPo> collect = coalflowHisPos.stream().sorted(Comparator.comparing(KsjjHisPo::getDataTime).reversed()).collect(Collectors.toList());
        for (KsjjHisPo coalflowHisPo : collect) {
            dateList.add(coalflowHisPo.getDataTime());
            bigDecimalList.add(coalflowHisPo.getPointValue());
        }
        chartDateVo.setDate(dateList);
        chartDateVo.setValue(bigDecimalList);
        return chartDateVo;
    }

    /**
     * 条件查询历史数据测点列表
     * @param pointDto
     * @return
     */
    @Override
    public List<PointHistoryListVo> pointHistoryList(PointDto pointDto) {
        //1天内 日期间隔不做处理
        //1~3天 日期间隔5分钟 取最大值
        //3天~1月  日期间隔1小时 取最大值
        //超过1月  返回前端消息，查询时间范围为一个月

        //查询得数据集合
        List<KsjjHisPo> coalflowHisPos = null;

        String stateCode = "1";
        if (pointDto.getEndTime().getTime() - pointDto.getStartTime().getTime() <= 3600 * 24 * 1 * 1000L) {
            LambdaQueryWrapper<KsjjHisPo> queryWrapper = new LambdaQueryWrapper<>();
            //一天内得数据
            queryWrapper.ge(KsjjHisPo::getDataTime,pointDto.getStartTime());
            //结束时间
            queryWrapper.le(pointDto.getEndTime() != null, KsjjHisPo::getDataTime, pointDto.getEndTime());
            queryWrapper.eq(KsjjHisPo::getPointCode, pointDto.getPointCode());

            //煤矿编码
            queryWrapper.eq(StringUtils.isNotEmpty(pointDto.getMineCode()),KsjjHisPo::getMineCode,pointDto.getMineCode());
            coalflowHisPos = ksjjHisMapper.selectList(queryWrapper);
        } else if (pointDto.getEndTime().getTime() - pointDto.getStartTime().getTime() <= 3600 * 24 * 3 * 1000L) {
            //三天内得数据
            List<ChartDto> chartDtoList= ksjjHisMapper.selectOneDayList(pointDto);
            List<PointHistoryListVo> collect = chartDtoList.stream().map(t -> {
                PointHistoryListVo pointHistoryListVo = new PointHistoryListVo();
                pointHistoryListVo.setDate(t.getTime());
                pointHistoryListVo.setValue(t.getValue());
                pointHistoryListVo.setState(stateCode.equals(t.getState()) ? "正常" : "异常");
                pointHistoryListVo.setStateCode(t.getState());
                return pointHistoryListVo;
            }).collect(Collectors.toList());
            return collect;
        } else if (pointDto.getEndTime().getTime() - pointDto.getStartTime().getTime() <= 3600 * 24 * 31 * 1000L) {
            //1月内得数据
            List<ChartDto> chartDtoList= ksjjHisMapper.selectOneMonthList(pointDto);
            List<PointHistoryListVo> collect = chartDtoList.stream().map(t -> {
                PointHistoryListVo pointHistoryListVo = new PointHistoryListVo();
                pointHistoryListVo.setDate(t.getTime());
                pointHistoryListVo.setValue(t.getValue());
                pointHistoryListVo.setState(stateCode.equals(t.getState()) ? "正常" : "异常");
                pointHistoryListVo.setStateCode(t.getState());
                return pointHistoryListVo;
            }).collect(Collectors.toList());
            return collect;
        }

        if (coalflowHisPos.isEmpty()) {
            return new ArrayList<>();
        }
        //list 降序排列
        List<KsjjHisPo> collect = coalflowHisPos.stream().sorted(Comparator.comparing(KsjjHisPo::getDataTime).reversed()).collect(Collectors.toList());
        List<PointHistoryListVo> collectVo = collect.stream().map(t -> {
            PointHistoryListVo pointHistoryListVo = new PointHistoryListVo();
            pointHistoryListVo.setDate(t.getDataTime());
            pointHistoryListVo.setValue(t.getPointValue());
            pointHistoryListVo.setState(stateCode.equals(t.getPointStatus().toString()) ? "正常" : "异常");
            pointHistoryListVo.setStateCode(t.getPointStatus().toString());
            return pointHistoryListVo;
        }).collect(Collectors.toList());
        return collectVo;
    }
}
